import { useState, useMemo, forwardRef, useImperativeHandle, useEffect } from 'react';
import { Form } from 'antd';
import CustomTabs from '../components/CustomTabs';
import Initiator from './Initiator';
import OpButton from './OpButton';
import Field from '../components/Field';
import Advance from './Advance';
import { defaultPlussignActions, defaultStrategyValue, getInitialRestartValue, getJumpRuleValue, getInitButtons, defaultReturnsBackButtonConfig } from '../../utils';

const CountersignTask = forwardRef((props: any, ref) => {
    const { userTaskData, curElement } = props;
    const [curTab, setCurTab] = useState('initiator');
    const [form] = Form.useForm();

    const customTabsData = useMemo(() => {
        return [
            {
                value: 'initiator',
                label: '审批人',
                disabled: false,
            },
            {
                value: 'button',
                label: '审批按钮',
                disabled: false,
            },
            {
                value: 'field',
                label: '字段权限',
                disabled: false,
            },
            {
                value: 'advance',
                label: '高级设置',
                disabled: false,
            },
        ]
    }, []);

    const formItems: any = useMemo(() => {
        return [
            {
                key: 'initiator',
                component: Initiator,
            },
            {
                key: 'button',
                component: OpButton,
            },
            {
                key: 'field',
                component: Field,
            },
            {
                key: 'advance',
                component: Advance,
            },
        ]
    }, []);

    useEffect(() => {
        let _curData = userTaskData?.find((item: { activityId: string; }) => item?.activityId == curElement?.id) || null;
        // let restart: string[] = [];
        // if (_curData?.buttonSetting?.isReturnStarter) {
        //     restart?.push('isReturnStarter');
        // };
        // if (_curData?.buttonSetting?.isCdirectBack) {
        //     restart?.push('isCdirectBack');
        // };
        _curData = {
            ..._curData,
            baseInfo: {
                ..._curData?.baseInfo,
                taskName: _curData?.baseInfo?.taskName || curElement?.businessObject?.name,
                isCounterSignNode: true,
            },
            buttonSetting: {
                ..._curData?.buttonSetting,
                // restart,
                inReturnsBack: _curData?.buttonSetting?.inReturnsBack == undefined ?
                    (_curData?.buttonSetting?.isReturnToDesignator == true || _curData?.buttonSetting?.isReturnStarter == true || _curData?.buttonSetting?.isCdirectBack == true) ?
                        true : false : _curData?.buttonSetting?.inReturnsBack ?? _curData?.buttonSetting?.actions?.find((item: { action: string; }) => item?.action == 'returnsBack')?.enable ?? false,
                // plusSign: _curData?.buttonSetting?.plusSign ?? _curData?.buttonSetting?.actions?.find((item: { action: string; }) => item?.action == 'plusSign')?.enable ?? false,
                actions: getInitButtons('ctSignTask', _curData?.buttonSetting?.actions),
                returnsBackButtonConfig: _curData?.buttonSetting?.returnsBackButtonConfig ?? defaultReturnsBackButtonConfig,
            },
            assembly: _curData?.assembly || [],
            senior: {
                ..._curData?.senior,
                jumpRule: getJumpRuleValue(_curData?.senior),
                automaticIntervar: _curData?.senior.automaticIntervar ? typeof _curData?.senior.automaticIntervar == 'string' ? JSON.parse(_curData?.senior.automaticIntervar) : _curData?.senior.automaticIntervar : {},
                isPushReachMsg: _curData?.senior?.isPushReachMsg ?? false,
                isPushCandidateMsg: _curData?.senior?.isPushCandidateMsg ?? false,
                isPushAssignMsg: _curData?.senior?.isPushAssignMsg ?? false,
                isPushReturnMsg: _curData?.senior?.isPushReturnMsg ?? false,
                isPushTimeOutMsg: _curData?.senior?.isPushTimeOutMsg ?? false,
                isPushUrgingMsg: _curData?.senior?.isPushUrgingMsg ?? false,
                isPushCancelMsg: _curData?.senior?.isPushCancelMsg ?? false,
                isPushEndMsg: _curData?.senior?.isPushEndMsg ?? false,
            },
        };
        form.setFieldsValue(_curData);
        setCurTab('initiator');
    }, [curElement, userTaskData]);

    useImperativeHandle(ref, () => ({
        form,
    }));

    const onChange = (value: any, values: any) => {
        const _curData = userTaskData?.find((item: { activityId: string; }) => item?.activityId == curElement?.id) || null;
        const performerType = value?.baseInfo?.performerType;
        const ccCategory = value?.baseInfo?.ccCategory;
        const automaticUrge = value?.senior?.automaticUrge;
        const returnsBack = values?.buttonSetting?.actions?.find((item: { action: string; }) => item?.action == 'returnsBack')?.enable;
        form.setFieldValue(['buttonSetting', 'inReturnsBack'], returnsBack);
        const plusSign = values?.buttonSetting?.actions?.find((item: { action: string; }) => item?.action == 'plusSign')?.enable;
        form.setFieldValue(['buttonSetting', 'plusSign'], plusSign);
        if (performerType == 'vars') {
            form.setFieldValue(['baseInfo', 'assignee'], '');
        };
        if (performerType == 'user' || performerType == 'userGroup' || performerType == 'position' || performerType == 'dept') {
            form.setFieldValue(['baseInfo', 'assignee'], []);
        };
        if (ccCategory == '1') {
            form.setFieldValue(['baseInfo', 'ccRules'], _curData?.baseInfo?.ccRules || true);
            form.setFieldValue(['baseInfo', 'ccMember'], _curData?.baseInfo?.ccMember || []);
        };
        if (automaticUrge) {
            form.setFieldValue(['senior', 'automaticIntervar'], _curData?.senior?.automaticIntervar || defaultStrategyValue);
        };
        // if (returnsBack === true) {
        //     if (!values?.buttonSetting?.isReturnToDesignator) {
        //         form.setFieldValue(['buttonSetting', 'isReturnToDesignator'], _curData?.buttonSetting?.isReturnToDesignator ?? false);
        //     };
        //     if (!values?.buttonSetting?.restart) {
        //         form.setFieldValue(['buttonSetting', 'restart'], getInitialRestartValue(_curData?.buttonSetting) || []);
        //     };
        // };
        // if (plusSign === true) {
        //     if (!values?.buttonSetting?.plusSignLogic) {
        //         form.setFieldValue(['buttonSetting', 'plusSignLogic'], _curData?.buttonSetting?.plusSignLogic || 'skipCurrent');
        //     };
        //     if (!values?.buttonSetting?.signingRules) {
        //         form.setFieldValue(['buttonSetting', 'signingRules'], _curData?.buttonSetting?.signingRules ?? false);
        //     };
        //     if (!values?.buttonSetting?.plussignActions) {
        //         form.setFieldValue(['buttonSetting', 'plussignActions'], _curData?.buttonSetting?.plussignActions || defaultPlussignActions);
        //     };
        // };
    };

    return (
        <>
            <CustomTabs tabs={customTabsData} onChange={setCurTab} curTab={curTab} />
            <Form
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                labelAlign='left'
                labelWrap={true}
                layout={'horizontal'}
                form={form}
                onValuesChange={onChange}
            >
                <Form.Item label='任务标识' name={['activityId']} hidden={true} />
                {
                    formItems?.map((item: { component: any; key: string }) => {
                        return (
                            <div style={{ display: curTab == item.key ? 'block' : 'none' }}>
                                <item.component {...props} form={form} />
                            </div>
                        )
                    })
                }
            </Form>
        </>
    );
});

export default CountersignTask;